Skip to main content

Paginating Queries

Some queries may take longer due to requesting a large amount of data. Pagination is useful for taking a large query and splitting it up into smaller chunks.

  • Pagination is useful to you because it allows for more flexibility when creating queries and improves performance
  • It's useful to end users that will feel like their information is loading faster.
  • it's useful to us because it makes responses easier to handle.

It's a win-win-win!​

Our pagination implementation makes use of two values; offset and limit.​

  • Offset refers to what index to start searching at
  • Limit refers to the total number of items that will be returned

Let's take a look at a specific example​

What if we wanted to make a query to see the current location of all 50 of our account's BinBars

Without Pagination
// Query for all BinBar's id and last reported location
const currentLocationQuery = `
query currentLocation {
currentUser {
account {
binBars {
id
lastLocation {
latitude
longitude
radius
}
# Some 'BinBar' fields omitted for brevity
}
}
}
}
`;
// This is querying for a lot of data that would take a long time
response = await runQuery(currentLocationQuery, {}, authorization);
const binBars = response.data.currentUser.account.binBars;

This previous implementation will not work for us. We need a better implementation. We need pagination.​

Let's say that we want to return the BinBars of all locations in groups of 10. Since there are 50 BinBars that would mean we would receive 5 groups. Easy, right? Here's what that looks like:

OffsetLimitReceived
0100-9
101010-19
201020-29
301030-39
401040-49

Now let's take a look at the implementation

With Pagination
// Query for all BinBar's id and last reported location
const currentLocationQuery = `
query currentLocation($page: PaginationInput!) {
currentUser {
account {
binBars(page: $page) {
id
lastLocation {
latitude
longitude
radius
}
# Some 'BinBar' fields omitted for brevity
}
}
}
}
`;

let results = [];
let offset = 0;
const limit = 10;
const max = 50;

// With this, all queries will be run simultaneously
for (let i = 0; i < max; i += limit) {
results.push(
runQuery(
currentLocationQuery,
{ page: { offset: offset, limit: limit } },
authorization,
),
);
}

// This waits for all of the queries to complete before progressing
const response = await Promise.all(results);
// From here, you can parse through response to find the last location of all of your BinBars quickly!
tip

To find one of anything, use pagination with a limit of 1